package com.cordys.uc.webapps.translator;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.w3c.dom.NodeList;

public class TranslationLogger {

    private static final String LOGDELIM = "`";
    private static HashMap xlmap = new HashMap();
    public static String EXCEPTIONLOGFILE ;
    public static BufferedWriter wrlog_exception;
    public static String EXCELFILE="";
    
    static {
        //writer for EXCEPTION log
        wrlog_exception = openLog(EXCEPTIONLOGFILE);
    }

    static void setExcelFile(String excelfile)
    {
        EXCELFILE=excelfile;
    }
    
    private static BufferedWriter openLog(String logfile) {
        BufferedWriter out = null;
        try {
            // Create file
            FileWriter fstream = new FileWriter(logfile);
            out = new BufferedWriter(fstream);
        } catch (Exception e) {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
        return out;
    }

    static void writetoXL(String filename, ArrayList<String> xldata) {
        String xlfile=EXCELFILE;
        InputStream inp = null;

        try {
            if (new File(xlfile).exists()) {
                inp = new FileInputStream(xlfile);
            }
            Workbook wb = null;
            if (inp == null) {
                wb = new HSSFWorkbook();
            } else {
                try {
                    wb = WorkbookFactory.create(inp);
                } catch (InvalidFormatException ex) {
                }
            }

            Sheet sheet;
            if (wb.getNumberOfSheets() > 0) {
                sheet = wb.getSheetAt(0);
            } else {
                wb.createSheet();
                sheet = wb.createSheet("LABEL");

            }
            Row row;
            Cell cell;
            int i = sheet.getLastRowNum();

            File ftmp = new File(filename);

            if (!ftmp.exists()) {
                return;


            }
            String t = ftmp.getAbsolutePath().substring(0, ftmp.getAbsolutePath().lastIndexOf(File.separator));

            if (!xlmap.containsKey(filename)) {
                row = sheet.createRow(++i);
                cell = row.createCell(0);
                cell.setCellValue("FILE");

                cell = row.createCell(1);
                cell.setCellValue("");

                cell = row.createCell(2);
                cell.setCellValue(ftmp.getName());

                cell = row.createCell(3);
                cell.setCellValue(ftmp.getName().substring(ftmp.getName().lastIndexOf(".") + 1));

                cell = row.createCell(4);

                cell.setCellValue(t.substring(t.lastIndexOf(File.separator) + 1));
            }
            xlmap.put(filename, "");
            for (String textnode : xldata) {
                if (!textnode.replaceAll("\\\\|\\<|\\>|\\t|\\r|\\n|\\r\\n|\\s|&nbsp;", "").trim().isEmpty()) {// && textnode.matches("(?:[a-z][a-z]+)")) {
                    row = sheet.createRow(++i);
                    cell = row.createCell(0);

                    if (textnode.trim().charAt(1) == '>' || textnode.trim().charAt(1) == '<') {
                        cell.setCellValue(textnode.trim().substring(2, textnode.length() - 2).replaceAll("\\\\|\\<|\\>|\\t|\\r|\\n|\\r\\n|&nbsp;", "").trim());
                        System.out.println(textnode.trim().substring(2, textnode.length() - 2).replaceAll("\\\\|\\<|\\>|\\t|\\r|\\n|\\r\\n|&nbsp;", "").trim());
                    } else {
                        cell.setCellValue(textnode.trim().substring(1, textnode.length() - 2).replaceAll("\\\\|\\<|\\>|\\t|\\r|\\n|\\r\\n|&nbsp;", "").trim());
                        System.out.println(textnode.trim().substring(1, textnode.length() - 2).replaceAll("\\\\|\\<|\\>|\\t|\\r|\\n|\\r\\n|&nbsp;", "").trim());
                    }
                }
            }

            if (inp != null) {
                inp.close();
            }
            // Write the output to a file
            FileOutputStream fileOut = new FileOutputStream(xlfile);
            wb.write(fileOut);
            fileOut.close();
        } catch (IOException ex) {
        } finally {
            try {
                if (inp != null) {
                    inp.close();
                }
            } catch (IOException ex) {
            }
        }
    }

    static void log(String id, String file, int lno, String line) {
        try {

            wrlog_exception.write(id + LOGDELIM + new File(file).getName() + LOGDELIM + new File(file).getAbsolutePath() + LOGDELIM + (lno) + LOGDELIM + line + "\r\n");

        } catch (IOException ex) {
        }
    }
    
    static void writeCafLabelstoXL(String filename,NodeList nodelist)
    {
    	int iterator=0;
    	ArrayList<String> xldata = new ArrayList();
    	int labelCount=0;
        for(iterator=0;iterator<nodelist.getLength();iterator++)
        {
            if((!nodelist.item(iterator).getTextContent().trim().equals(""))		
               )
            {
                if(nodelist.item(iterator).getTextContent().trim().contains("\n"))
                {
	                String x[]=nodelist.item(iterator).getTextContent().trim().split("\n");
	                for(int m=0;m<x.length;m++)
	                	{
		                	if((!(x[m].trim().equals("")))) //&& !(x[m].trim().equals("\n"))
		                	{
		                		xldata.add("<"+x[m].trim()+"/>");
		                      	labelCount++;
		                	}
	                	
	                   	}
                }
                else
                {
                	xldata.add("<"+nodelist.item(iterator).getTextContent().trim()+"/>"); //set cell value
                	labelCount++;
                }
                
                
            }
        }
        writetoXL(filename,xldata);
    }
}
